package com.cakebackoffice;


import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.cakebackoffice.Model.CatalogCategory;
import com.cakebackoffice.Model.MenuType;
import com.cakebackoffice.Model.ProductType;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class CatalogMenuFragment extends Fragment {
    private CatalogCategory thisIsRoot;

    private List<Long> childCategoriesId = new ArrayList<Long>();
    private List<Long> childProductsId = new ArrayList<Long>();
    private List<Long> childMenusId = new ArrayList<Long>();

    private List<CatalogCategory> childCategories = new ArrayList<CatalogCategory>();
    private List<ProductType> childProducts = new ArrayList<ProductType>();
    private List<MenuType> childMenus = new ArrayList<MenuType>();

    private List<Object> objectList = new ArrayList<Object>();
    private Stack<Long> categoryIdStack = new Stack<Long>();

    private Button buttonAddCategory;
    private Button buttonAddProduct;
    private Button buttonAddMenu;


    private ListView lv;


    // View Methods
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        CatalogCategory requestResult = null;
        if ((requestResult = CatalogCategory.getOneFromRemoteID(getActivity().getBaseContext(), 1l)) == null) {
            thisIsRoot = new CatalogCategory("Root", "Root Of Catalog !");
            thisIsRoot.saveToDatabase(getActivity().getBaseContext());
        } else {
            thisIsRoot = requestResult;
        }


        View mainView = inflater.inflate(R.layout.catalog_menu, container, false);

        buttonAddCategory = (Button) mainView.findViewById(R.id.buttonAddCategory);
        buttonAddCategory.setOnClickListener(onNewCategoryButtonClickListenneur);

        buttonAddProduct = (Button) mainView.findViewById(R.id.buttonAddProctuctType);
        buttonAddProduct.setOnClickListener(onNewProductButtonClickListenneur);

        buttonAddMenu = (Button) mainView.findViewById(R.id.buttonAddMenu);
        buttonAddMenu.setOnClickListener(onNewMenuButtonClickListenneur);

        return mainView;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {


        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();


        switch (item.getItemId()) {
            case R.id.button_delete:
                setAlertBeforeDelete(lv.getItemAtPosition((int) info.id));
                return true;
            default:

                return super.onContextItemSelected(item);
        }


    }

    private void setAlertBeforeDelete(final Object objectToDelete) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Please, confirm to delete.")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        try {
                            ((CatalogMenuActivity) getActivity()).deleteObject(objectToDelete);
                        } catch (Exception e) {
                            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
                        }

                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.menu_delete, menu);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.

        this.lv = (ListView) getActivity().findViewById(R.id.ListView);
        getCategory(thisIsRoot.getIdDB(), true);
        lv.setOnItemClickListener(lvListenner);
        registerForContextMenu(this.lv);


    }

    // Listenners

    private ListView.OnItemClickListener lvListenner = new ListView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            // On récupére l'objet sélectionné
            Object object = adapterView.getItemAtPosition(i);
            if (object instanceof CatalogCategory) {
                Toast toast = Toast.makeText(getActivity().getBaseContext(), "Displaying the category: " + ((CatalogCategory) object).getName(), Toast.LENGTH_SHORT);
                toast.show();
                getCategory(((CatalogCategory) object).getIdDB(), true);
                ((CatalogMenuActivity) getActivity()).onListViewCategoryClick((CatalogCategory) object);
            } else if (object instanceof ProductType) {
                ((CatalogMenuActivity) getActivity()).onListViewProductClick((ProductType) object);


            } else if (object instanceof MenuType) {
                ((CatalogMenuActivity) getActivity()).onListViewMenuClick((MenuType) object);
            } else {
                if (categoryIdStack.size() > 1) {
                    categoryIdStack.pop();
                    getCategory(categoryIdStack.lastElement(), false);
                } else {
                    Toast toast = Toast.makeText(getActivity().getBaseContext(), "You are already to the root of the catalog!", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }


        }
    };

    // Pour les boutons:

    private View.OnClickListener onNewCategoryButtonClickListenneur = new View.OnClickListener() {
        public void onClick(View v) {
            ((CatalogMenuActivity) getActivity()).openDialogNewCategory();
            getCategory(categoryIdStack.lastElement(), false);
        }
    };

    private View.OnClickListener onNewProductButtonClickListenneur = new View.OnClickListener() {
        public void onClick(View v) {
            ((CatalogMenuActivity) getActivity()).openDialogNewProduct();
            getCategory(categoryIdStack.lastElement(), false);
        }
    };

    private View.OnClickListener onNewMenuButtonClickListenneur = new View.OnClickListener() {
        public void onClick(View v) {
            ((CatalogMenuActivity) getActivity()).openDialogNewMenu();
            getCategory(categoryIdStack.lastElement(), false);
        }
    };


    public void getCategory(Long dirPath, Boolean dir)

    {
        objectList.clear();
        childCategories.clear();
        childProducts.clear();
        childMenus.clear();


        if (dir) {
            // Ici on avance dans le catalogue
            categoryIdStack.add(dirPath);
        }

        // Ajout du retour
        objectList.add("...");

        // On récupére les objets à partir des ids
        childCategoriesId = CatalogCategory.getOne(getActivity().getBaseContext(), dirPath).getChildCategoriesId();
        for (Long l : childCategoriesId) {
            childCategories.add(CatalogCategory.getOne(getActivity().getBaseContext(), l));
        }
        childProductsId = CatalogCategory.getOne(getActivity().getBaseContext(), dirPath).getChildProductTypeId();
        for (Long l : childProductsId) {
            childProducts.add(ProductType.getOne(getActivity().getBaseContext(), l));
        }

        childMenusId = CatalogCategory.getOne(getActivity().getBaseContext(), dirPath).getChildMenuTypeId();
        for (Long l : childMenusId) {
            childMenus.add(MenuType.getOne(getActivity().getBaseContext(), l));
        }


        // Ajout des catégories.
        for (int i = 0; i < childCategories.size(); i++) {
            objectList.add(childCategories.get(i));
        }

        // Ajout des Menus.
        for (int i = 0; i < childMenus.size(); i++) {
            if (childMenus.get(i) != null)
                objectList.add(childMenus.get(i));
        }

        // Ajout des produits
        for (int i = 0; i < childProducts.size(); i++) {
            if (childProducts.get(i) != null)
                objectList.add(childProducts.get(i));
        }


        ListAdapter adapter = new ListViewCatalogAdapter(getActivity().getBaseContext(), R.layout.file_row, objectList);
        this.lv.setAdapter(adapter);

        ((CatalogMenuActivity) getActivity()).setIdActualCategory(dirPath);
    }


}
